package com.weir.resources.permissions.map;

import ch.hsr.geohash.GeoHash;

import java.util.Arrays;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class GeoHashUtils {

    private static final Logger LOGGER = LoggerFactory.getLogger(GeoHashUtils.class);

    /**
     * 将经纬度转换为geoHash
     * @param longtitude
     * @param latitude
     * @param precision
     * @return
     */
    public static String toGeoHash(double longtitude, double latitude, int precision) {
        try {
            return GeoHash.withCharacterPrecision(latitude,longtitude, precision).toBase32();
        } catch (Exception e) {
            return "";
        }
    }

    /**
     * 将geoHash转换为经纬度
     * @param geoHash
     * @return
     */
    public static double[] toLngAndLat(String geoHash) {
        if (geoHash == null || geoHash.isEmpty()) {
            return null;
        }

        GeoHash geo;
		try {
			geo = GeoHash.fromGeohashString(geoHash);
		} catch (Exception e) {
			return new double[] {0,0};
		}
        return new double[] {
                geo.getPoint().getLongitude(),
                geo.getPoint().getLatitude()
        };
    }

    /**
     * 获取geoHash周围的8个geoHash
     * @param geoHash
     * @param precision
     * @return
     */
    public static String[] getAroundGeoHash(String geoHash, int precision) {

        String[] geoHashs = new String[8];

        try {
            GeoHash[] around = GeoHash.fromGeohashString(geoHash).getAdjacent();
            for (int i = 0; i < around.length; ++i) {
                geoHashs[i] = around[i].toBase32().substring(0, precision);
            }
        } catch (Exception e) {
            LOGGER.info("getAroundGeoHash Exception: {} {}", geoHash,  e.getMessage());
            return new String[]{};
        }

        return geoHashs;
    }
    
    public static void main(String[] args) {
    	double[] ds = toLngAndLat("ws7nwu");
		System.out.println(ds[0]+","+ds[1]);
	}
}